<script setup lang="ts">
import RoomStatus from './components/room-status.vue'
import RoomAction from './components/room-action.vue'
import RoomMessage from './components/room-message.vue'
import { io } from 'socket.io-client'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onBeforeUnmount } from 'vue'
import type { chatMsgListApi, chatMsgListItem, patientConsultOrderDetailApi } from '@/types/room'
import { ref, nextTick } from 'vue'
import { MsgType } from '@/enums'
import { patientConsultOrderDetail } from '@/api/room'

const store = useUserStore()
const route = useRoute()

/*
  websocket
   1: 下载   yarn add socket.io-client
   2：导入插件  {io}
   3: 建立连接
   4：接收消息
   5：发送消息
   6：关闭连接
   ....

*/
// 建立连接
const socket = io(import.meta.env.VITE_APP_BASE_URL, {
  auth: {
    token: `Bearer ${store.userInfo?.token}`
  },
  query: {
    orderId: route.query.orderId
  }
})
// 监听是否连接成功
socket.on('connect', () => {
  console.log('连接成功')
})
// 连接错误
socket.on('error', err => {
  console.log('连接错误', err)
})
// 监听连接是否关闭
socket.on('disconnect', () => {
  console.log('关闭成功')
})
// 接收默认消息
const list = ref<chatMsgListItem[]>([])
socket.on('chatMsgList', (res: chatMsgListApi) => {
  const arr: chatMsgListItem[] = []
  res.data.forEach(item => {
    arr.push({
      createTime: item.createTime,
      msg: {
        content: item.createTime
      },
      msgType: MsgType.Notify,
      id: item.createTime
    })
    arr.push(...item.items)
  })
  // 数据循环处理时,响应式数据尽量只处理一次(尽量不要循环频繁改变响应式数据)
  list.value = arr
  console.log('接收的默认消息', res)
})
/*
 状态：
   1：定义api
   2:导入api
   3:进入页面调用api
   4:处理数据类型
   5：存储数据并渲染
*/
const orderInfo = ref<patientConsultOrderDetailApi>()
const getStatus = async () => {
  const res = await patientConsultOrderDetail(route.query.orderId as string)
  orderInfo.value = res.data
  console.log('状态数据', res)
}
// 监听websocket的状态变化
socket.on('statusChange', () => {
  getStatus()
})
getStatus()

// 接收消息
socket.on('receiveChatMsg', async (res: chatMsgListItem) => {
  list.value.push(res)
  console.log('接收 消息', res)
  // nextTick(() => {
  //   window.scrollTo(0, document.body.scrollHeight)
  // })
  await nextTick()
  window.scrollTo(0, document.body.scrollHeight)
})

// 发送文字消息
const sendMsg = (msg: string) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderInfo.value!.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: msg
    }
  })
  console.log(msg)
}
// 发送图片信息
const sendImage = (imgInfo: { id: string; url: string }) => {
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderInfo.value!.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: imgInfo
    }
  })
}

// 离开时关闭连接
onBeforeUnmount(() => {
  socket.close()
})
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 状态栏 -->
    <RoomStatus v-if="orderInfo" :orderInfo="orderInfo"></RoomStatus>
    <!-- 聊天区域 -->
    <RoomMessage v-if="orderInfo" :list="list" :orderInfo="orderInfo"></RoomMessage>
    <!-- 发送信息 -->
    <RoomAction
      v-if="orderInfo"
      :orderInfo="orderInfo"
      @sendMsg="sendMsg"
      @sendImage="sendImage"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
